// HistoryGraph.cpp : implementation file
//

#include "stdafx.h"
#include "ASUI.h"
#include "HistoryGraph.h"
#include "afxdialogex.h"
#include "Windows.h"
#include "Time.h"

#include <GdiPlus.h>

// HistoryGraph dialog

IMPLEMENT_DYNAMIC(HistoryGraph, CDialog)

HistoryGraph::HistoryGraph(CWnd* pParent /*=NULL*/)
	: CDialog(HistoryGraph::IDD, pParent)
{
	startTime = COleDateTime::GetCurrentTime();
	endTime = COleDateTime::GetCurrentTime();
}

HistoryGraph::~HistoryGraph()
{
}

void HistoryGraph::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_SENSOR_ID_COMBO, sensorIdCombo);
	DDX_Control(pDX, IDC_READING_TYPE_COMBO, readingTypeCombo);
	DDX_Control(pDX, IDC_Chart, chart);
	DDX_Control(pDX, IDC_DATETIMEPICKER_START, startDateTime);
	DDX_Control(pDX, IDC_DATETIMEPICKER_END, endDateTime);
}


BEGIN_MESSAGE_MAP(HistoryGraph, CDialog)
	ON_BN_CLICKED(IDC_SAVEBUTTON, &HistoryGraph::OnBnClickedSavebutton)
	ON_CBN_SELCHANGE(IDC_SENSOR_ID_COMBO, &HistoryGraph::OnCbnSelchangeSensorIdCombo)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DATETIMEPICKER_START, &HistoryGraph::OnDtnDatetimechangeDatetimepicker1)
	ON_CBN_SELCHANGE(IDC_READING_TYPE_COMBO, &HistoryGraph::OnCbnSelchangeReadingTypeCombo)
	ON_NOTIFY(DTN_DATETIMECHANGE, IDC_DATETIMEPICKER_END, &HistoryGraph::OnDtnDatetimechangeDatetimepickerEnd)
END_MESSAGE_MAP()

BOOL HistoryGraph::OnInitDialog()
{
	CDialog::OnInitDialog();

	Time startTime = Time::today();
	Time endTime(startTime.getUnixTime() + 60 * 60 * 24);

	CString idString;
	std::set<int> ids = readingInformation->getSensorIds(startTime, endTime);
	for (std::set<int>::iterator iter=ids.begin(); iter != ids.end(); iter++) {
		idString.Format("%d", *iter);
		TRACE("%d", *iter);
		sensorIdCombo.AddString(idString);
	}
	SetDropDownHeight(&sensorIdCombo, 50);
	sensorIdCombo.SetCurSel(0);
	OnCbnSelchangeSensorIdCombo();

	std::set<std::string> readingTypes = readingInformation->getReadingTypes();
	for (std::set<std::string>::iterator iter=readingTypes.begin(); iter != readingTypes.end(); iter++) {
		if ((*iter) != "Parent") {
			readingTypeCombo.AddString((*iter).c_str());
		}
	}
	SetDropDownHeight(&readingTypeCombo, 50);
	readingTypeCombo.SetCurSel(0);
	OnCbnSelchangeReadingTypeCombo();

	CTime startDate;
	startDateTime.GetTime(startDate);

	chart.setStartTime(unique_ptr<ITime>(new Time(startTime)));
	chart.setEndTime(unique_ptr<ITime>(new Time(endTime)));
	
	COleDateTime dtMin;
	COleDateTime dtMax;

	//would change this to start date
	dtMin = COleDateTime(1995,1,1,0,0,0);
    dtMax = COleDateTime(endTime.getUnixTime());

	startDateTime.SetRange(&dtMin, &dtMax);

	 dtMin = COleDateTime(startTime.getUnixTime());
    dtMax = COleDateTime::GetCurrentTime();
	
	endDateTime.SetRange(&dtMin, &dtMax);

	return true;
}

void HistoryGraph::SetDropDownHeight(CComboBox* pMyComboBox, int itemsToShow)
{
  //Get rectangles
  CRect rctComboBox, rctDropDown;
  //Combo rect
  pMyComboBox->GetClientRect(&rctComboBox); 
  //DropDownList rect
  pMyComboBox->GetDroppedControlRect(&rctDropDown); 

  //Get Item height
  int itemHeight = pMyComboBox->GetItemHeight(-1); 
  //Converts coordinates
  pMyComboBox->GetParent()->ScreenToClient(&rctDropDown); 
  //Set height
  rctDropDown.bottom = rctDropDown.top + rctComboBox.Height() + itemHeight*itemsToShow; 
  //apply changes
  pMyComboBox->MoveWindow(&rctDropDown); 
}

void HistoryGraph::OnBnClickedSavebutton()
{
	SYSTEMTIME SysTime;
	GetLocalTime(&SysTime);
	wchar_t filename[200];
	memset(filename,0,sizeof(filename));
	wsprintfW(filename,L"screen%02d:%02d:%02d h.jpeg",SysTime.wHour,SysTime.wMinute,SysTime.wSecond);
	gdiscreen();
}

void HistoryGraph::gdiscreen()
{
   using namespace Gdiplus;
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   {
   HDC scrdc, memdc;
   HBITMAP membit;
   scrdc = ::GetDC(0);
   
   int Height;// = GetSystemMetrics(SM_CYSCREEN);
   int Width;// = GetSystemMetrics(SM_CXSCREEN);
   RECT rect1;
	GetWindowRect(&rect1);
   CRect rect;
	CWnd *pWnd = GetDlgItem(IDC_Chart);
	pWnd->GetWindowRect(&rect);
	ScreenToClient(&rect); //optional step - see below
	Height = rect.Height()-10;
	Width = rect.Width()-5;
	//position:  rect.left, rect.top
	//size: rect.Width(), rect.Height()
	int left,top;
	left = rect.left+ rect1.left+5;
	top = rect.top+ rect1.top+30;
   memdc = CreateCompatibleDC(scrdc);
   membit = CreateCompatibleBitmap(scrdc, Width, Height);
   HBITMAP hOldBitmap =(HBITMAP) SelectObject(memdc, membit);
   BitBlt(memdc, 0, 0, Width, Height, scrdc, left, top, SRCCOPY);

   Gdiplus::Bitmap bitmap(membit, NULL);

   CLSID clsid;
   GetEncoderClsid(L"image/jpeg", &clsid);

   
     CFileDialog FileDialog(FALSE,
                            "jpeg",
                            NULL,
                            OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
                            "Picture Files (.jpeg)|.jpeg|All Files (.)|*.*||");

     if(FileDialog.DoModal() == IDOK)
     {
		 
	   CString PathName = (FileDialog.GetPathName());
       WCHAR*    wcString;

       wcString = new WCHAR[PathName.GetLength()+1];
       MultiByteToWideChar(CP_ACP, 0, PathName.GetBuffer(0), -1, wcString, PathName.GetLength()+1);    
	   
       bitmap.Save(wcString, &clsid);

		 
	   
       SelectObject(memdc, hOldBitmap);

       DeleteObject(memdc);

       DeleteObject(membit);

       ::ReleaseDC(0,scrdc); 
   }
   
}

   GdiplusShutdown(gdiplusToken);
}



int HistoryGraph::GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
	using namespace Gdiplus;
	UINT  num = 0;          // number of image encoders
	UINT  size = 0;         // size of the image encoder array in bytes

	ImageCodecInfo* pImageCodecInfo = NULL;

	GetImageEncodersSize(&num, &size);
	if(size == 0)
		return -1;  // Failure

	pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
	if(pImageCodecInfo == NULL)
		return -1;  // Failure

	GetImageEncoders(num, size, pImageCodecInfo);

	for(UINT j = 0; j < num; ++j)
	{
		if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
		{
			*pClsid = pImageCodecInfo[j].Clsid;
			free(pImageCodecInfo);
			return j;  // Success
		}    
	}

	free(pImageCodecInfo);
	return 0;
}





void HistoryGraph::OnCbnSelchangeSensorIdCombo()
{
	CString idString;
	int index = sensorIdCombo.GetCurSel();
	sensorIdCombo.GetLBText(index, idString);
	chart.setSensorId(atoi(idString));

 	chart.RedrawWindow();
}

//start date
void HistoryGraph::OnDtnDatetimechangeDatetimepicker1(NMHDR *pNMHDR, LRESULT *pResult)
{

	LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	// TODO: Add your control notification handler code here
	
	*pResult = 0;
	TRACE("Start day: %d", pDTChange->st.wDay);

	CTime startDate;
	startDateTime.GetTime(startDate);
	//use for set range so user has to pick a time after the start date
	COleDateTime dtMin;
	COleDateTime dtMax;
	COleDateTime endMin, endMax;

	//would change this to start date
	dtMin = COleDateTime(1995,1,1,0,0,0);
    dtMax = COleDateTime(endTime);
	
	startDateTime.SetRange(&dtMin, &dtMax);
	startDateTime.GetTime(startDate);
	startTime =  COleDateTime(startDate.GetTime());
	endMin = COleDateTime(startTime);
	endMax = COleDateTime::GetCurrentTime();
	endDateTime.SetRange(&endMin,&endMax);
	chart.setStartTime(unique_ptr<ITime>(new Time(startDate.GetYear(), startDate.GetMonth(), startDate.GetDay()-1)));
	


	chart.RedrawWindow();
}

//end date
void HistoryGraph::OnDtnDatetimechangeDatetimepickerEnd(NMHDR *pNMHDR, LRESULT *pResult)
{
	//CString t = COleDateTime::
	LPNMDATETIMECHANGE pDTChange = reinterpret_cast<LPNMDATETIMECHANGE>(pNMHDR);
	
	*pResult = 0;
	CTime date;
	endDateTime.GetTime(date);
	//use for set range so user has to pick a time after the start date
	COleDateTime dtMin;
	COleDateTime dtMax, startMin,startMax;
	
	//would change this to start date
    dtMin = COleDateTime(startTime);
    dtMax = COleDateTime::GetCurrentTime();
	endTime =  COleDateTime(date.GetTime());
	
	endDateTime.SetRange(&dtMin, &dtMax);
	startMin = COleDateTime(2010,1,1,0,0,0);
	startMax = COleDateTime(endTime);//COleDateTime(COleDateTime(date.GetTime()));
	startDateTime.SetRange(&startMin, &startMax);
	endDateTime.GetTime(date);
	chart.setEndTime(unique_ptr<ITime>(new Time(date.GetYear(), date.GetMonth(), date.GetDay())));

	chart.RedrawWindow();

}

void HistoryGraph::OnCbnSelchangeReadingTypeCombo()
{
	CString readingType;
	int index = readingTypeCombo.GetCurSel();
	readingTypeCombo.GetLBText(index, readingType);
	TRACE("ReadingType = %s", readingType);
	chart.setReadingType((LPCTSTR)readingType);

	chart.RedrawWindow();
}